package com.example.front.controller;

import com.example.common.constant.AndonCode;
import com.example.common.constant.SendWeChatMessage;
import com.example.front.dto.Analysis.XunfeiDto;
import com.example.front.dto.CraftSearchDto;
import com.example.front.entity.Incident;
import com.example.front.serivce.IncidentService;
import com.example.front.until.PcmPlayer;
import com.example.front.until.TimesUntil;
import com.example.front.until.TtsTool;
import com.example.passport.dto.sql.Sql;
import com.example.passport.entity.Tenant;
import com.example.passport.entity.User;
import com.example.passport.mapper.SqlMapper;
import com.example.passport.mapper.TenantMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: scx
 * @Date: 2022/5/3 12:19
 */

@Api(tags = "数据分析")
@RestController
@CrossOrigin
@RequestMapping("/front/analysis")
public class AnalysisController {

    @Resource
    SqlMapper sqlMapper;
    @Resource
    TenantMapper tenantMapper;
    @Resource
    IncidentService incidentService;

    @Value("${com.sun.yuyinFilePath}")
    private String yuyinFilePath;

//    @ApiOperation("获取当天报警次数最多的盒子")
//    @GetMapping("/dayMost")
//    public void dayMost() {
//        String nowDay = TimesUntil.nowDay();
//
//        List<Tenant> tenantList = tenantMapper.findAll();
//
//
//        for (Tenant tenant : tenantList) {
//            String strSql = "SELECT *, count( * ) AS count  FROM incident " +
//                    "where created_at BETWEEN '" + nowDay + " 00:00:00" + "' and '" + nowDay + " 23:59:59" + "'" +
//                    " and tenant_id = " + tenant.getId() + " and processing_status != " + AndonCode.ANDON_CANCEL.getCode() +
//                    " GROUP BY box_id  ORDER BY count DESC ";
//            List<Sql> sqlList = sqlMapper.dynamicsSelect(strSql);
//
//            //incident 没有数据直接跳过
//            if (sqlList == null || sqlList.size() <= 0) {
//                continue;
//            }
//
//            String select_incident_day = "SELECT * FROM incident_day where days = '" + nowDay + "' and tenant_id = '" + tenant.getId() + "'";
//            List<Sql> incidentDayList = sqlMapper.dynamicsSelect(select_incident_day);
//
//            //已经存在当天的数据
//            if (incidentDayList != null && incidentDayList.size() > 0) {
//                //比较incident_day count是否大于incident count
//                if (incidentDayList.get(0).getCount() > sqlList.get(0).getCount()) {
//                    continue;
//                } else if (incidentDayList.get(0).getCount() == sqlList.get(0).getCount()) {
//                    String select_count = "SELECT * FROM incident " +
//                            "where created_at BETWEEN '" + nowDay + " 00:00:00" + "' and '" + nowDay + " 23:59:59" + "' and tenant_id = '" + tenant.getId() + "'" +
//                            "GROUP BY box_id HAVING count(*) = " + sqlList.get(0).getCount();
//                    List<Sql> selectCountList = sqlMapper.dynamicsSelect(select_count);
//                    if (selectCountList.size() == incidentDayList.size()) {
//                        continue;
//                    }
//                }
//                //大于 删除incident_day
//                String delete_incident_day = "delete FROM incident_day where days = '" + nowDay + "' and tenant_id = '" + tenant.getId() + "'";
//                sqlMapper.dynamicsDelete(delete_incident_day);
//            }
//
//            Sql topSql = sqlList.get(0);
//            for (Sql sql : sqlList) {
//                if (topSql.getCount() == sql.getCount()) {
//                    String insertSql = "INSERT into incident_day (`incident_id`,`days`,`tenant_id`,`count`) " +
//                            "VALUES ('" + sql.getId() + "','" + nowDay + "', '" + sql.getTenantId() + "' , '" + sql.getCount() + "')";
//                    sqlMapper.dynamicsInsert(insertSql);
//                } else {
//                    continue;
//                }
//            }
//        }
//
//    }

    @ApiOperation("获取当天报警次数最多的盒子")
    @GetMapping("/dayMost")
    public void dayMost() {
        List<Tenant> tenantList = tenantMapper.findAll();

        String nowDay = TimesUntil.nowDay();

        for (Tenant tenant : tenantList) {
            List<Sql> sqlList = is_sql(nowDay + " 00:00:00", nowDay + " 23:59:59", nowDay, "incident_day", tenant);

            if (sqlList == null) {
                continue;
            }

            Sql topSql = sqlList.get(0);
            for (Sql sql : sqlList) {
                if (topSql.getCount() == sql.getCount()) {
                    String insertSql = "INSERT into incident_day (`box_id`,`days`,`tenant_id`,`count`) " +
                            "VALUES ('" + sql.getBoxId() + "','" + nowDay + "', '" + sql.getTenantId() + "' , '" + sql.getCount() + "')";
                    sqlMapper.dynamicsInsert(insertSql);
                } else {
                    break;
                }
            }

        }

    }


//    @ApiOperation("获取当月报警次数最多的盒子")
//    @GetMapping("/monthMost")
//    public void monthMost() {
//
//        List<Tenant> tenantList = tenantMapper.findAll();
//
//        //获取当前月份
//        String nowYearMonth = TimesUntil.nowYearMonth();
//        String nowMonth = TimesUntil.nowMonth();
//
//        for (Tenant tenant : tenantList) {
//            String strSql = "SELECT * FROM incident_day " +
//                    "where days = '" + nowYearMonth + "'" +
//                    " and tenant_id = " + tenant.getId() +
//                    " ORDER BY count DESC ";
//            List<Sql> sqlList = sqlMapper.dynamicsSelect(strSql);
//
//            if (sqlList == null || sqlList.size() <= 0) {
//                continue;
//            }
//
//            String select_incident_month = "SELECT * FROM incident_month where days = '" + nowYearMonth + "' and tenant_id = '" + tenant.getId() + "'";
//            List<Sql> incidentMonthList = sqlMapper.dynamicsSelect(select_incident_month);
//
//            //已经存在当天的数据
//            if (incidentMonthList != null && incidentMonthList.size() > 0) {
//                //比较incident_day count是否大于incident count
//                if (incidentMonthList.get(0).getCount() < sqlList.get(0).getCount()) {
//                    //大于 删除incident_day
//                    String delete_incident_day = "delete FROM incident_month where days = '" + nowYearMonth + "' and tenant_id = '" + tenant.getId() + "'";
//                    sqlMapper.dynamicsDelete(delete_incident_day);
//                } else if (incidentMonthList.get(0).getCount() == sqlList.get(0).getCount()) { //count相等跳过
//                    continue;
//                }
//            }
//
//            Sql topSql = sqlList.get(0);
//            for (Sql sql : sqlList) {
//                if (topSql.getCount() == sql.getCount()) {
//                    String insertSql = "INSERT into incident_day (`incident_id`,`days`,`tenant_id`,`count` , `months`) " +
//                            "VALUES ('" + sql.getIncidentId() + "','" + sql.getDays() + "', '" + sql.getTenantId() + "' , '" + sql.getCount() + "' , '" + nowMonth + "')";
//                    sqlMapper.dynamicsInsert(insertSql);
//                } else {
//                    continue;
//                }
//            }
//
//
//        }
//
//    }


    @ApiOperation("获取当月报警次数最多的盒子")
    @GetMapping("/monthMost")
    public void monthMost() {

        List<Tenant> tenantList = tenantMapper.findAll();

        String s = TimesUntil.nowMonth();
        String firstDayOfMonth = TimesUntil.getFirstDayOfMonth(Integer.parseInt(s));
        String lastDayOfMonth = TimesUntil.getLastDayOfMonth(Integer.parseInt(s));

        String nowYearMonth = TimesUntil.nowYearMonth();
        String nowMonth = TimesUntil.nowMonth();

        for (Tenant tenant : tenantList) {
            List<Sql> sqlList = is_sql(firstDayOfMonth, lastDayOfMonth, nowYearMonth + "-01", "incident_month", tenant);

            if (sqlList == null) {
                continue;
            }

            Sql topSql = sqlList.get(0);
            for (Sql sql : sqlList) {
                if (topSql.getCount() == sql.getCount()) {
                    String insertSql = "INSERT into incident_month (`box_id`,`days`,`tenant_id`,`count` , `months`) " +
                            "VALUES ('" + sql.getBoxId() + "','" + nowYearMonth + "-01" + "', '" + sql.getTenantId() + "' , '" + sql.getCount() + "' , '" + nowMonth + "')";
                    sqlMapper.dynamicsInsert(insertSql);
                } else {
                    break;
                }
            }
        }
    }


    @ApiOperation("获取当季报警次数最多的盒子")
    @GetMapping("/quarterMost")
    public void QuarterMost() {

        List<Tenant> tenantList = tenantMapper.findAll();

        String s = TimesUntil.nowMonth();
        String firstDayOfQuarter = TimesUntil.getFirstDayOfQuarter(Integer.parseInt(s));
        String lastDayOfQuarter = TimesUntil.getLastDayOfQuarter(Integer.parseInt(s));
        String s1 = firstDayOfQuarter.split(" ")[0];
        String quarter = TimesUntil.getQuarter(Integer.parseInt(s));

        for (Tenant tenant : tenantList) {
            List<Sql> sqlList = is_sql(firstDayOfQuarter, lastDayOfQuarter, s1, "incident_quarter", tenant);

            if (sqlList == null) {
                continue;
            }

            Sql topSql = sqlList.get(0);
            for (Sql sql : sqlList) {
                if (topSql.getCount() == sql.getCount()) {
                    String insertSql = "INSERT into incident_quarter (`box_id`,`days`,`tenant_id`,`count` , `quarters`) " +
                            "VALUES ('" + sql.getBoxId() + "','" + s1 + "', '" + sql.getTenantId() + "' , '" + sql.getCount() + "' , '" + quarter + "')";
                    sqlMapper.dynamicsInsert(insertSql);
                } else {
                    break;
                }
            }
        }
    }

    @ApiOperation("获取当年报警次数最多的盒子")
    @GetMapping("/yearMost")
    public void yearMost() {

        List<Tenant> tenantList = tenantMapper.findAll();

        String year = TimesUntil.nowYear();

        for (Tenant tenant : tenantList) {
            List<Sql> sqlList = is_sql(year + "-01-01 00:00:00", year + "-12-31 23:59:59", year + "-01-01", "incident_year", tenant);

            if (sqlList == null) {
                continue;
            }

            Sql topSql = sqlList.get(0);
            for (Sql sql : sqlList) {
                if (topSql.getCount() == sql.getCount()) {
                    String insertSql = "INSERT into incident_year (`box_id`,`days`,`tenant_id`,`count` , `years`) " +
                            "VALUES ('" + sql.getBoxId() + "','" + year + "-01-01" + "', '" + sql.getTenantId() + "' , '" + sql.getCount() + "' , '" + year + "')";
                    sqlMapper.dynamicsInsert(insertSql);
                } else {
                    break;
                }
            }
        }
    }


    public List<Sql> is_sql(String dateStart, String dateEnd, String likeDate, String dataBase, Tenant tenant) {

        String strSql = "SELECT *, count( * ) AS count  FROM incident " +
                "where created_at BETWEEN '" + dateStart + "' and '" + dateEnd + "'" +
                " and tenant_id = " + tenant.getId() + " and processing_status != " + AndonCode.ANDON_CANCEL.getCode() +
                " and status != " + User.STATUS_DELETE +
                " GROUP BY box_id  ORDER BY count DESC ";
        List<Sql> sqlList = sqlMapper.dynamicsSelect(strSql);

        //incident 没有数据直接跳过
        if (sqlList == null || sqlList.size() <= 0) {
            return null;
        }

        String select_incident_day = "SELECT * FROM " + dataBase + " where days like '%" + likeDate + "%' and tenant_id = '" + tenant.getId() + "'";
        List<Sql> incidentDayList = sqlMapper.dynamicsSelect(select_incident_day);

        //已经存在当天的数据
        if (incidentDayList != null && incidentDayList.size() > 0) {
            //比较incident_day count是否大于incident count
            if (incidentDayList.get(0).getCount() > sqlList.get(0).getCount()) {
                return null;
            } else if (incidentDayList.get(0).getCount() == sqlList.get(0).getCount()) {
                String select_count = "SELECT * FROM incident " +
                        "where created_at BETWEEN '" + dateStart + "' and '" + dateEnd + "' and tenant_id = '" + tenant.getId() + "'" +
                        "GROUP BY box_id HAVING count(*) = " + sqlList.get(0).getCount();
                List<Sql> selectCountList = sqlMapper.dynamicsSelect(select_count);
                if (selectCountList.size() == incidentDayList.size()) {
                    return null;
                }
            }
            //大于 删除incident_day
            String delete_incident_day = "delete FROM " + dataBase + " where days like '%" + likeDate + "%' and tenant_id = '" + tenant.getId() + "'";
            sqlMapper.dynamicsDelete(delete_incident_day);
        }

        return sqlList;

    }


    @ApiOperation("获取当年报警次数最多的盒子")
    @GetMapping("/xunfeiTTs")
    public void xunfeiTTs(XunfeiDto xunfeiDto) {
        System.out.println(xunfeiDto.getUuid());
        File file = new File(yuyinFilePath + "\\" + xunfeiDto.getUuid() + ".pcm");
        PcmPlayer.playPcm(file);
    }

    @ApiOperation("测试")
    @GetMapping("/test")
    public void test() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");

        String content = "<div class=\\\"gray\\\">" + formatter.format(new Date()) + "</div> " +
                "<div>" + "请注意, SC16,B10,工位,质量 ,呼叫" + "</div>" +
                "<div>未处理</div>";

        SendWeChatMessage weChat = new SendWeChatMessage();
    }


    @ApiOperation("自动推送超时处理的报警内容")
    @GetMapping("/wxOverTime")
    public void wxOverTime() throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date date = new SimpleDateFormat("yyyy-MM-dd").parse(df.format(new Date()));
    }


}
